package org.robot.scm.platform.server.handler;

import static org.robot.scm.platform.server.LockKey.LAST_KEY;
import static org.robot.scm.platform.server.LockKey.LOCK_KEY;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Objects;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.infra.LocalCacheHelper;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.registry.HikariRegistry;
import org.robot.scm.platform.registry.TelegramRegistry;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.server.ExecuteParam;
import org.robot.scm.pojos.platform.server.SshMySql;
import org.robot.scm.utils.JsonHelper;

@Slf4j
@NoArgsConstructor
public class RemoveHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/removeTask";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("POST")) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }

        // 结束正在执行的sql
        this.stopExecute();

        // 清理redis
        RedisCacheHelper.remove(LOCK_KEY, LAST_KEY);

        // 本地日志
        LocalCacheHelper.clear();

        // 清理sqlLike
        TelegramRegistry.clearSqlLike();

        sendSuccessResponse(exchange, "任务清除成功");
    }

    private void stopExecute() {
        BaseConfig config = super.config(PlatformEnum.SQL);
        ExecuteParam param = JsonHelper.toObject(RedisCacheHelper.get(LOCK_KEY), ExecuteParam.class);
        if (Objects.isNull(param)) {
            return;
        }
        param.initParams().forEach(aws -> {
            SshMySql sshMysql = config.getCurrentPlatform().getSshMysql(aws);
            HikariDataSource dataSource = HikariRegistry.getHikariMap().get(sshMysql.getName());
            if (Objects.isNull(dataSource)) {
                return;
            }
            try (Connection connection = dataSource.getConnection()) {
                Statement statement = connection.createStatement();
                statement.cancel();
                statement.close();
            } catch (Exception e) {
                log.warn("正在执行的脚本取消失败", e);
            }
        });
    }

}
